<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="分类名称" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="导航栏显示状态" prop="navStatus">
        <el-select v-model="queryParams.navStatus" placeholder="导航栏显示状态" clearable size="mini">
          <el-option v-for="dict in navStatusOptions" :key="dict.value" :label="dict.label" :value="+dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="分类层级" prop="level">
        <el-select v-model="queryParams.level" placeholder="分类层级" clearable size="mini">
          <el-option v-for="dict in protuctCategoryLevelOptions" :key="dict.value" :label="dict.label"
                     :value="+dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPerm="['beauty:productCategory:add']">新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading" :data="productCategoryList" row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="name" label="分类名称" width="260"></el-table-column>
      <el-table-column prop="level" label="分类层级" width="260"></el-table-column>
      <el-table-column prop="navStatus" label="导航栏显示状态" width="260">
        <template slot-scope="{row}">
          <el-tag v-if="row.navStatus === 1" type="success">显示</el-tag>
          <el-tag v-else type="info">不显示</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="图标" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.icon==''">暂无</span>
          <el-image v-else :src="scope.row.icon" style="width: 40px; height: 40px" fit="fill"
                    :preview-src-list="[scope.row.icon]"/>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="200"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="gmtCreate" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPerm="['beauty:productCategory:edit']" v-if="scope.row.level != 0">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
                     v-hasPerm="['beauty:productCategory:add']">新增
          </el-button>
          <el-button v-if="scope.row.level != 0 " size="mini" type="text" icon="el-icon-delete"
                     @click="handleDelete(scope.row)" v-hasPerm="['beauty:productCategory:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="图标" prop="icon">
              <el-upload class="up-img-uploader" :action="imageAction" :show-file-list="false"
                         :on-success="handleUploadSuccess" :headers="headers">
                <img v-if="imageUrl" :src="imageUrl" class="up-img" alt="">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级分类" prop="parentId">
              <tree-select v-model="form.parentId" :options="productCategoryOptions" :normalizer="normalizer"
                           placeholder="选择上级分类"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入分类名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导航栏显示状态" prop="navStatus">
              <el-radio-group v-model="form.navStatus">
                <el-radio v-for="dict in navStatusOptions" :key="dict.value" :label="+dict.value">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类层级" prop="level">
              <el-radio-group v-model="form.level">
                <el-radio v-for="dict in protuctCategoryLevelOptions" :key="dict.value" :label="+dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  addProductCategory,
  delProductCategory,
  getProductCategory, getProductCategoryOptionSelect,
  getProductCategoryTreeList,
  listProductCategory,
  updateProductCategory
} from '@a/beauty/productCategory'
import { getToken } from '@u/auth'

export default {
  name: 'ProductCategory',
  components: { TreeSelect },
  data() {
    return {
      imageUrl: null, // 上传图片回显
      headers: {
        // 上传文件的请求头
        Authorization: 'Bearer ' + getToken()
      },
      // 请求地址
      imageAction: process.env.VUE_APP_BASE_API + process.env.VUE_APP_FILE_UPLOAD, // 上传的图片服务器地址
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      productCategoryList: [],
      // 树选项
      productCategoryOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      navStatusOptions: [],
      // 商品分类级别
      protuctCategoryLevelOptions: [],
      // 查询参数
      queryParams: {
        name: undefined,
        navStatus: undefined,
        level: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: '上级分类不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '分类顺序不能为空', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '分类图标不能为空', trigger: 'blur' }
        ],
        navStatus: [
          { required: true, message: '导航栏显示状态不能为空', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '分类层级不能为空', trigger: 'blur' }
        ]
      }
    }

  },
  created() {
    this.getList()
    this.getDictItems('beauty_product_category_status').then(response => {
      this.navStatusOptions = response.data
    })
    this.getDictItems('beauty_product_category_level').then(response => {
      this.protuctCategoryLevelOptions = response.data.filter(item => item.value != 0)
    })
  }
  ,
  methods: {
    /** 上传封面成功 **/
    handleUploadSuccess(res, file) {
      if (res.code == 200) {
        const { url } = res.data
        this.msgNoticeSuccess('上传成功')
        this.imageUrl = url
        this.form.icon = url
      }
    }
    ,
    /** 查询列表 */
    getList() {
      this.loading = true
      listProductCategory(this.queryParams).then(response => {
        let list = response.data
        this.productCategoryList = this.handleTree(list)
        this.loading = false
      })
    }
    ,
    /**数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    }
    ,
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        name: undefined,
        icon: undefined,
        sort: 0,
        level: 1,
        navStatus: 0
      }
      this.imageUrl = undefined
      this.resetForm('form')
    }
    ,
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    }
    ,
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    }
    ,
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (row != undefined) {
        this.form.parentId = row.id
      }
      this.open = true
      this.title = '添加商品分类'
      getProductCategoryOptionSelect().then(response => {
        let rootNode = {
          id: 0,
          parentId: -1,
          name: '顶级分类',
          level: 0
        }
        let list = response.data
        list.push(rootNode)
        // 只要两层
        this.productCategoryOptions = this.handleTree(list.filter(item => item.level != 3))
      })
    }
    ,
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getProductCategory(row.id).then(response => {
        this.form = response.data
        // 回显图片
        this.imageUrl = this.form.icon
        this.open = true
        this.title = '修改商品分类'
      })
      getProductCategoryOptionSelect().then(response => {
        let rootNode = {
          id: 0,
          parentId: -1,
          name: '顶级分类',
          level: 0
        }
        let list = response.data
        list.push(rootNode)
        // 只要两层
        this.productCategoryOptions = this.handleTree(list.filter(item => item.level != 3))
      })
    }
    ,
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateProductCategory(this.form).then(response => {
              this.msgNoticeSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addProductCategory(this.form).then(response => {
              this.msgNoticeSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delProductCategory(row.id)
      }).then(() => {
        this.getList()
        this.msgNoticeSuccess('删除成功')
      })
    }
  }
}
</script>
<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.up-img-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #000000;
  background-color: #e8e8e8;
  width: 170px;
  height: 170px;
  line-height: 170px;
  text-align: center;
}

.up-img {
  width: 170px;
  height: 170px;
  display: block;
}
</style>
